const {
  GamesModel
} = require('../../../utils/games-model.js');
const gamesModel = new GamesModel();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page: 1,
    pageSize: 10,
    totalCount: 0,
    games: [],
    isLoadData: false,
    loadText: ''
  },

  goGameDetail (e) {
    const { item } = e.currentTarget.dataset
    if (item.options.link) {
      if (item.options.redirect_type == '1') {
        wx.navigateToMiniProgram({
          appId: item.options.app_id,
          path: item.options.link,
          extraData: {},
          envVersion: 'release',
          success(res) { }
        })
      } else {
        wx.navigateTo({
          url: item.options.link,
        })
      }
    }
  },

  getGameList () {
    const merchantId = wx.getStorageSync('merchantId')
    return new Promise((resolve, reject) => {
      gamesModel.getGameLists({
        merchantId,
        moduleTypes: [7],
        limit: this.data.pageSize,
        offset: (this.data.page - 1) * this.data.pageSize
      }).then(data => {
        resolve({
          data: data.data,
          totalCount: data.totalCount
        })
      }).catch(err => {
        wx.showToast({
          title: `${err.error}`,
          icon: 'none'
        })
      })
    })
  },
  scrollEnd() {
    if (this.data.games.length >= this.data.totalCount) {
      this.setData({
        isLoadData: true,
        loadText: "已经到底了"
      })
    } else {
      this.setData({
        page: this.data.page + 1,
        isLoadData: true,
        loadText: "加载中..."
      })
      this.getGameList().then(data => {
        this.setData({
          games: this.data.games.concat(data.data),
          totalCount: data.totalCount
        })
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getGameList().then(data => {
      this.setData({
        games: this.data.games.concat(data.data),
        totalCount: data.totalCount
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})